# Copyright (C) 2025 All rights reserved.
#   
# @File message.py
# @Brief 
# @Author 杨嘉祥, vnimy@mediad.cn
# @Version 1.0
# @Date 2025-01-26
#
import frappe
from frappe.core.doctype.user.user import generate_keys
from frappe.utils.oauth import get_oauth_keys
from frappe.utils.password import get_decrypted_password
from .wxworkapi.CorpApi import *


@frappe.whitelist(allow_guest=True)
def callback():
    pass


def send_wxwork_message(users, doc):
    doc = frappe._dict(doc)
    social_login_key = frappe.db.get_single_value("WXWork Settings", "social_login_key")

    if not social_login_key:
        return
    
    client = get_oauth_keys(social_login_key)
    agentid = frappe.db.get_value("Social Login Key", social_login_key, "wxwork_agentid")
    corpid = client.get("client_id")
    corpsecret = client.get("client_secret")
    
    userids = frappe.get_list(
        "WXWork User", {"corpid": corpid, "user": ["in", users]}, pluck="userid"
    )
    for userid in userids:
        api = CorpApi(corpid, corpsecret)
        data = {
            "touser": userid,
            "agentid": agentid,
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800,
        }
        if doc.message_type == "Markdown":
            data.update(
                {
                    "msgtype": "markdown",
                    "markdown": {"content": doc.content},
                }
            )
        else:
            data.update(
                {
                    "msgtype": "text",
                    "text": {"content": doc.content},
                }
            )
        response = api.httpCall(CORP_API_TYPE["MESSAGE_SEND"], data)
        # msgid = response.get("msgid")
